package com.m3958.firstgwt.client.utils;

import com.google.gwt.core.client.JsArray;
import com.google.gwt.user.client.Timer;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.m3958.firstgwt.client.datasource.AsyncTaskDataSource;
import com.m3958.firstgwt.client.types.AsyncTaskField;
import com.m3958.firstgwt.client.types.SmartOperationName;
import com.m3958.firstgwt.shared.type.SmartParameterName;
import com.m3958.gwtutil.clientside.client.AjaxResult;
import com.m3958.gwtutil.clientside.client.SmartFetchPara;
import com.m3958.gwtutil.clientside.client.interfac.IwantAjaxResult;
import com.m3958.gwtutil.clientside.client.jso.AsyncTaskJso;
import com.m3958.gwtutil.clientside.client.utils.HttpAjax;
import com.smartgwt.client.util.SC;

@Singleton
public class AsyncTaskQuery implements IwantAjaxResult{
	
	@Inject
	private HttpAjax ajax;
	
	private SmartFetchPara sfp = null;
	
	private boolean inProgress = false;

	 // A keeper of the timer instance in case we need to cancel it
	private Timer repeatTimer = null;

	static final int TIMEOUT = 30; // 30 second timeout
	
	private SmartFetchPara getSfp(){
		if(sfp == null){
			sfp = new SmartFetchPara();
			sfp.putSmartCfudUrl();
			sfp.putModelName(AsyncTaskDataSource.className);
			sfp.putOpType(SmartOperationName.FETCH.getValue());
			sfp.put(AsyncTaskField.NOTIFIED.getValue(), false);
			sfp.put(SmartParameterName.FETCH_OWNER,true);
		}
		return sfp;
	}

	public void startWork () {
	    // Check to make sure the timer isn't already running.
		if (repeatTimer != null) {
			return;
		}

	    // Create a timer to abort if the RPC takes too long
	    repeatTimer = new Timer() {
	    	public void run() {
	    		if(inProgress)return;
	    		inProgress = true;
	    		ajax.fetch(getSfp().getMap(), AsyncTaskQuery.this, "asyncTaskQuery");
//	        repeatTimer = null;
	    	}
	    };

	    // (re)Initialize the abort flag and start the timer.
//	    timeoutTimer.schedule(TIMEOUT * 1000); // timeout is in milliseconds
	    
	    repeatTimer.scheduleRepeating(TIMEOUT * 1000);

	    // Kick off an RPC
//	    myService.myRpcMethod(arg, new AsyncCallback() {
//
//	      public void onFailure(Throwable caught) {
//	         Window.alert("RPC Failed:" + caught);
//	         cancelTimer();
//	      }
//
//	      public void onSuccess(Object result) {
//	         cancelTimer();
//	         if (abortFlag) {
//	           // Timeout already occurred. discard result
//	           return;
//	         }
//	         Window.alert ("RPC returned: "+ (String)result);
//	      }
//	    }
	  }

	  // Stop the timeout timer if it is running
	  public void cancelTimer() {
	    if (repeatTimer != null) {
	       repeatTimer.cancel();
	       repeatTimer = null;
	    }
	  }

	@Override
	public void onAjaxDataArrival(AjaxResult ar) {
		inProgress = false;
		JsArray<AsyncTaskJso> atjs = ar.getSmartResponseJso().getDataArray().cast();
		int openTasks = 0;
		int closedTasks = 0;
		for(int i=0;i<atjs.length();i++){
			AsyncTaskJso atj = atjs.get(i);
			if("SUCCESS".equals(atj.getStatus()) || "FAILURE".equals(atj.getStatus())){
				closedTasks++;
			}else{
				openTasks++;
			}
		}
		if(closedTasks > 0){
			SC.warn("您提交的任务已结束！<a href=\"#async_task\">查看</a>");
		}
		if(openTasks == 0){
			cancelTimer();
		}
	}
}
